package person.bing.fbcloud.common.core.xss.wrappers;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @author: mengfanbing
 * @date: 2020/5/4 16:51
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private static final String XSS_IGNORE_STR = "_edt";
    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getHeader(String name){
        return HtmlUtil.escape(super.getHeader(name));
    }

    @Override
    public String getQueryString(){
        return HtmlUtil.escape(super.getQueryString());
    }

    @Override
    public String getParameter(String name){
        String val = super.getParameter(HtmlUtil.escape(name));
        if (StrUtil.isEmpty(val) || val.endsWith(XSS_IGNORE_STR)){
            return val;
        }else{
            return HtmlUtil.escape(val);
        }
    }

    @Override
    public String[] getParameterValues(String name){
        String[] values = super.getParameterValues(name);
        if (!name.endsWith(XSS_IGNORE_STR)){
            if (values != null){
                int length = values.length;
                String[] escapseValues = new String[length];
                for (int i=0;i<length;i++){
                    escapseValues[i] = HtmlUtil.escape(values[i]);
                }
                return  escapseValues;
            }
        }
        return values;
    }

    //TODO 不想写了 -o-!
    /*@Override
    public ServletInputStream getInputStream() throws IOException{

    }
*/
}
